package com.easefun.polyv.livecommon.ui.util;


import android.text.TextUtils;
import android.util.Log;

import com.alibaba.android.arouter.launcher.ARouter;
import com.easefun.polyv.livecommon.module.config.PLVLiveChannelConfigFiller;
import com.google.gson.Gson;
import com.plv.foundationsdk.net.PLVResponseBean;
import com.plv.foundationsdk.net.PLVResponseExcutor;
import com.plv.foundationsdk.net.PLVRetrofitHelper;
import com.plv.foundationsdk.net.PLVrResponseCallback;
import com.plv.livescenes.config.PLVLiveChannelType;
import com.plv.livescenes.feature.login.IPLVSceneLoginManager;
import com.plv.livescenes.feature.login.PLVLiveLoginResult;
import com.plv.livescenes.feature.login.PLVPlaybackLoginResult;
import com.plv.livescenes.feature.login.PLVSceneLoginManager;
import com.plv.livescenes.playback.video.PLVPlaybackListType;
import com.plv.thirdpart.blankj.utilcode.util.ToastUtils;

import okhttp3.OkHttpClient;

public class PLVLoginUtils {
    /**
     * 登陆
     *
     * @param channelId  频道id
     * @param userId     用户id
     * @param userName   用户名称
     * @param userAvatar 用户头像  网络地址
     */
    public static String HUDONG = "https://h5-dev.mangguonews.com/livewebview/index.html";
//    public static String HUDONG = "http://192.168.1.132:26001/index.html";
    public static String GOODS = "https://h5-dev.mangguonews.com/livewebview/product.html";
    public static String TUWEN = "https://h5-dev.mangguonews.com/livewebview/tuwen.html";
    private String channelId = "";
    private String userId = "";
    private String userName = "";
    private String userAvatar = "";
    private String userid = "92367c0508";
    private String appid = "gc3985k7el";
    private String appsecret = "39eb92e6712b4327885bde8a34f59a34";
    private int likes = 0;//点赞数
    private int count = 0;//观看人数
    private boolean isLogin = true;
    private static PLVLoginUtils plvLoginUtils;
    private static PLVSceneLoginManager plvSceneLoginManager;
    private PLVLoginListener loginListener;

    public String getUserId() {
        return userId;
    }

    public String getUserid() {
        return userid;
    }

    public String getAppid() {
        return appid;
    }

    public String getAppsecret() {
        return appsecret;
    }

    public String getChannelId() {
        return channelId;
    }

    public boolean isLogin() {
        return isLogin;
    }

    public static PLVLoginUtils initUtils() {
        if (plvLoginUtils == null) {
            plvLoginUtils = new PLVLoginUtils();
        }
        return plvLoginUtils;
    }

    public PLVLoginUtils configUrl(String urlType) {
        if (plvLoginUtils == null) {
            new Throwable("请先调用initUtils方法初始化");
        }
        HUDONG = "https://h5-" + urlType + ".mangguonews.com/livewebview/index.html";
        GOODS = "https://h5-" + urlType + ".mangguonews.com/livewebview/product.html";
        TUWEN = "https://h5-" + urlType + ".mangguonews.com/livewebview/tuwen.html";
        return plvLoginUtils;
    }

    public PLVLoginUtils configUrl(String webUrlHUDONG, String webUrlGOODS, String webUrlTUWEN) {
        if (plvLoginUtils == null) {
            new Throwable("请先调用initUtils方法初始化");
        }
        HUDONG = webUrlHUDONG;
        GOODS = webUrlGOODS;
        TUWEN = webUrlTUWEN;
        return plvLoginUtils;
    }

    public PLVLoginUtils configSecret(String userid, String appid, String appsecret) {
        if (plvLoginUtils == null) {
            new Throwable("请先调用initUtils方法初始化");
        }
        this.userid = userid;
        this.appid = appid;
        this.appsecret = appsecret;
        return plvLoginUtils;
    }

    public PLVLoginUtils setLoginListener(PLVLoginListener listener) {
        if (plvLoginUtils == null) {
            new Throwable("请先调用initUtils方法初始化");
        }
        this.loginListener = listener;
        return plvLoginUtils;
    }

    //设置点赞数
    public PLVLoginUtils clickLike(int likes) {
        if (plvLoginUtils == null) {
            new Throwable("请先调用initUtils方法初始化");
        }
        this.likes = likes;
        return plvLoginUtils;
    }

    //是否登录  true  登陆  false 未登录
    public PLVLoginUtils setLoginStatus(boolean isLogin, OnOtherClickListener onOtherClickListener) {
        this.isLogin = isLogin;
        this.onOtherClickListener = onOtherClickListener;
        return this;
    }

    //设置观看人数
    public PLVLoginUtils lookCount(int count) {
        if (plvLoginUtils == null) {
            new Throwable("请先调用initUtils方法初始化");
        }
        this.count = count;
        return plvLoginUtils;
    }

    public void sendMsgStatus(boolean status) {
        OnSendMsgStatusListener onSendMsgStatusListener = getOnSendMsgStatusListener();
        if (onSendMsgStatusListener != null) {
            onSendMsgStatusListener.onSendMsgStatus(status);
        }
    }

    public void login(final String channelId, final String userId, final String userName, final String userAvatar, final OnLoginStatusListener onLoginStatusListener) {
        if (TextUtils.isEmpty(channelId) || TextUtils.isEmpty(userId) || TextUtils.isEmpty(userName)) {
            ToastUtils.showShort("channelId 、userId 、userName不能为空！");
            return;
        }
        AppManager.getAppManager().finishAllActivity();
        this.channelId = channelId;
        this.userId = userId;
        this.userName = userName;
        this.userAvatar = userAvatar;
        PLVLiveChannelConfigFiller.setupAccount(userid, appid, appsecret);
        plvSceneLoginManager = new PLVSceneLoginManager();
        OkHttpClient okHttpClient = PLVRetrofitHelper.userAgentOkHttpClient();
        PLVQueryApi api = PLVRetrofitHelper.createApi(PLVQueryApi.class, "https://api.polyv.net/", okHttpClient);
        long timestamp = System.currentTimeMillis();
        String sign = this.appsecret + "appId" + this.appid + "channelId" + channelId + "timestamp" + timestamp + this.appsecret;
        PLVResponseExcutor.excuteUndefinData(api.queryChannelInfo(this.appid, timestamp, MD5.encryption(sign), channelId), new PLVrResponseCallback<ChannelBean>() {
            @Override
            public void onSuccess(ChannelBean channelBean) {
                Log.d("----onSuccess---", new Gson().toJson(channelBean));
                if (200 == channelBean.getCode() && "success".equals(channelBean.getStatus())) {
                    ChannelBean data = channelBean.getData();
                    if (data != null) {
                        if ("playback".equals(data.getWatchStatus())) {
                            loginPlaybackNew(data.getNewScene(), data.getTemplate(),data.getBgImg(), onLoginStatusListener);
                        } else {
                            loginLiveNew(data.getNewScene(), data.getTemplate(), data.getBgImg(), onLoginStatusListener);
                        }
                    } else {
                        if (loginListener != null) {
                            loginListener.onFail("抱歉：获取信息失败，请向管理员反馈");
                        }
                    }
                } else {
                    onDestroy();
                    if (loginListener != null) {
                        loginListener.onFail("抱歉：登录失败，请向管理员反馈");
                    }
                }
            }

            @Override
            public void onFailure(PLVResponseBean<ChannelBean> responseBean) {
                super.onFailure(responseBean);
                ToastUtils.showShort(responseBean.getMessage() + "");
                if (loginListener != null) {
                    loginListener.onFail(responseBean.getMessage());
                }
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                ToastUtils.showShort("频道id有误！");
                if (loginListener != null) {
                    loginListener.onFail(e.getMessage());
                }
            }

            @Override
            public void onFinish() {

            }
        });

    }

    private void loginLiveNew(final String newScene, final String template, final String splashImg, final OnLoginStatusListener onLoginStatusListener) {
        plvSceneLoginManager.loginLiveNew(this.appid, this.appsecret, this.userid, channelId, new IPLVSceneLoginManager.OnLoginListener<PLVLiveLoginResult>() {
            @Override
            public void onLoginSuccess(PLVLiveLoginResult plvLiveLoginResult) {
                onLoginStatusListener.onLoginStatus("success", true);
                if ("alone".equals(newScene)) {
                    if ("portrait_alone".equals(template)) {
                        //竖屏
                        ARouter.getInstance().build("/PLVEC/PLVECLiveEcommerceActivity")
                                .withString("channelId", channelId)
                                .withString("viewerId", userId)
                                .withString("viewerName", userName)
                                .withString("viewerAvatar", userAvatar)
                                .withInt("likes", likes)
                                .withInt("count", count)
                                .withSerializable("channel_type", plvLiveLoginResult.getChannelTypeNew())
                                .withBoolean("is_live", true)
                                .navigation();
                        if (loginListener != null) {
                            loginListener.onSuccess();
                        }
                    } else {
                        //横屏
                        ARouter.getInstance().build("/PLVLC/PLVLCCloudClassActivity")
                                .withString("channelId", channelId)
                                .withString("viewerId", userId)
                                .withString("viewerName", userName)
                                .withString("viewerAvatar", userAvatar)
                                .withInt("likes", likes)
                                .withInt("count", count)
                                .withSerializable("channel_type", plvLiveLoginResult.getChannelTypeNew())
                                .withBoolean("is_live", true)
                                .navigation();
                        if (loginListener != null) {
                            loginListener.onSuccess();
                        }
                    }
                } else {
                    String splashUrl = "";
                    if (!TextUtils.isEmpty(splashImg)) {
                        splashUrl = "https:" + splashImg;
                    }
                    ARouter.getInstance().build("/PLVLC/PLVLCCloudClassActivity")
                            .withString("channelId", channelId)
                            .withString("viewerId", userId)
                            .withString("viewerName", userName)
                            .withString("viewerAvatar", userAvatar)
                            .withString("newScene", newScene)
                            .withString("splashImg", splashUrl)
                            .withInt("likes", likes)
                            .withInt("count", count)
                            .withSerializable("channel_type", plvLiveLoginResult.getChannelTypeNew())
                            .withBoolean("is_live", true)
                            .navigation();
                    if (loginListener != null) {
                        loginListener.onSuccess();
                    }
                }
                onDestroy();
            }

            @Override
            public void onLoginFailed(String s, Throwable throwable) {
                onLoginStatusListener.onLoginStatus(s, false);
                onDestroy();
                if (loginListener != null) {
                    loginListener.onFail(s);
                }
            }
        });
    }

    private void loginPlaybackNew(final String newScene, final String template, final String splash, final OnLoginStatusListener onLoginStatusListener) {
        plvSceneLoginManager.loginPlaybackNew(this.appid, this.appsecret, this.userid, channelId, "", new IPLVSceneLoginManager.OnLoginListener<PLVPlaybackLoginResult>() {
            @Override
            public void onLoginSuccess(PLVPlaybackLoginResult plvPlaybackLoginResult) {
                Log.d("----onLoginSuccess----", new Gson().toJson(plvPlaybackLoginResult));
                onLoginStatusListener.onLoginStatus("success", true);
                PLVLiveChannelType channelType = plvPlaybackLoginResult.getChannelTypeNew();
                //1.SDK中未开启点播列表时——默认选择“读取直播后台回放设置”的参数
                //2.SDK中开启“点播列表”/通过vid观看时——优先响应“点播列表”/vid观看开关配置
                PLVPlaybackListType plvPlaybackListType = PLVPlaybackListType.PLAYBACK;
                if ("alone".equals(newScene)) {
                    if ("portrait_alone".equals(template)) {
                        //竖屏
                        ARouter.getInstance().build("/PLVEC/PLVECLiveEcommerceActivity")
                                .withString("channelId", channelId)
                                .withString("viewerId", userId)
                                .withString("viewerName", userName)
                                .withString("viewerAvatar", userAvatar)
                                .withString("newScene",newScene)
                                .withSerializable("channel_type", plvPlaybackLoginResult.getChannelTypeNew())
                                .withBoolean("is_live", false)
                                .withSerializable("video_list_type", plvPlaybackListType)
                                .navigation();
                        if (loginListener != null) {
                            loginListener.onSuccess();
                        }
                    } else {
                        //横屏
                        ARouter.getInstance().build("/PLVLC/PLVLCCloudClassActivity")
                                .withString("channelId", channelId)
                                .withString("viewerId", userId)
                                .withString("viewerName", userName)
                                .withString("viewerAvatar", userAvatar)
                                .withSerializable("channel_type", channelType)
                                .withBoolean("is_live", false)
                                .withString("newScene",newScene)
                                .withSerializable("video_list_type", plvPlaybackListType)
                                .navigation();
                        if (loginListener != null) {
                            loginListener.onSuccess();
                        }
                    }
                } else {
                    String splashUrl = "";
                    if (!TextUtils.isEmpty(splash)) {
                        splashUrl = "https:" + splash;
                    }
                    ARouter.getInstance().build("/PLVLC/PLVLCCloudClassActivity")
                            .withString("channelId", channelId)
                            .withString("viewerId", userId)
                            .withString("viewerName", userName)
                            .withString("viewerAvatar", userAvatar)
                            .withString("newScene",newScene)
                            .withString("splashImg", splashUrl)
                            .withSerializable("channel_type", plvPlaybackLoginResult.getChannelTypeNew())
                            .withBoolean("is_live", false)
                            .withSerializable("video_list_type", plvPlaybackListType)
                            .navigation();
                    if (loginListener != null) {
                        loginListener.onSuccess();
                    }
                }
                onDestroy();
            }

            @Override
            public void onLoginFailed(String msg, Throwable throwable) {
                onLoginStatusListener.onLoginStatus(msg, false);
                if (loginListener != null) {
                    loginListener.onFail(msg);
                }
                onDestroy();
            }
        });
    }

    //发送消息监听
    private OnSendMsgListener onSendMsgListener;

    public void setOnSendMsgListener(OnSendMsgListener onSendMsgListener) {
        this.onSendMsgListener = onSendMsgListener;
    }

    public OnSendMsgListener getOnSendMsgListener() {
        return onSendMsgListener;
    }

    public interface OnSendMsgListener {
        void onSendMsg(String msg);
    }

    //发送消息状态监听
    private OnSendMsgStatusListener onSendMsgStatusListener;

    public OnSendMsgStatusListener getOnSendMsgStatusListener() {
        return onSendMsgStatusListener;
    }

    public void setOnSendMsgStatusListener(OnSendMsgStatusListener onSendMsgStatusListener) {
        this.onSendMsgStatusListener = onSendMsgStatusListener;
    }

    public interface OnSendMsgStatusListener {
        void onSendMsgStatus(boolean status);
    }

    public interface OnLoginStatusListener {
        /**
         * @param msg    信息
         * @param status 状态  true 成功  false 失败
         */
        void onLoginStatus(String msg, boolean status);
    }

    //分享监听
    private OnClickShareListener onShareListener;

    public OnClickShareListener getOnShareListener() {
        return onShareListener;
    }

    public void setOnShareListener(OnClickShareListener onShareListener) {
        this.onShareListener = onShareListener;
    }

    public interface OnClickShareListener {
        void onShare();
    }

    private void onDestroy() {
        if (plvSceneLoginManager != null) {
            plvSceneLoginManager.destroy();
            plvSceneLoginManager = null;
        }
    }

    //未登录 点击赞 和 发送礼物
    public OnOtherClickListener onOtherClickListener;

    public OnOtherClickListener getOnOtherClickListener() {
        return onOtherClickListener;
    }

    public interface OnOtherClickListener {
        void onOtherClick(String type);
    }
}
